#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 说明：自行将中英文混合文本按照中文、英文分段处理，全部使用`onnx`模式合成语音数据，然后按照原有顺序拼接起来。
# 速度快。
from queue import Full
import re,uuid
import sys,os,time
from flask import Flask, request, abort
import paddle
from paddlespeech.cli.asr import ASRExecutor
from paddlespeech.cli.text import TextExecutor

text_executor = TextExecutor()

asr_executor = ASRExecutor()

if len(sys.argv) == 2:
    text = asr_executor(
            model='conformer_wenetspeech',
            lang='zh',
            sample_rate=16000,
            config=None, 
            ckpt_path=None,
            audio_file=sys.argv[1],
            codeswitch=False,
            force_yes=True,
            device=paddle.get_device())
    result = text_executor(text=text, task='punc', model='ernie_linear_p7_wudao', lang='zh')
    print(text + "\n")

app = Flask("__name__")

@app.route("/api/asr", methods=["POST"])
def api_tts():
    name = request.form['name'].strip()
    if len(name)==0:
        return abort(404)
    if False == name.endswith(".wav"):
            return "?\n"
    try:
      info = os.stat(name)
      if info == None:
            return "?\n"
      if info.st_size > 400000:
            return abort(404)
    except:
         return "?\n"
    print("wav:"+name + "\n")
    try:
        text = asr_executor(
            model='conformer_wenetspeech',
            lang='zh',
            sample_rate=16000,
            config=None, 
            ckpt_path=None,
            audio_file=name,
            codeswitch=False,
            force_yes=True,
            device=paddle.get_device())
        result = text_executor(text=text, task='punc', model='ernie_linear_p7_wudao', lang='zh')
        return result
        #return text+"，"
    except:
        print(sys.exc_info())
        return "?\n"

if __name__ == '__main__':
    try:
        app.run(host="localhost", port=15060)
    except:
        print(sys.exc_info())
        print("崩溃\n")